"use client"

import React, { useCallback, useEffect, useRef, useState } from 'react'
import { cn } from '@/lib/utils'
import { createSecureLink } from '@/lib/utils/link-security'
import { ATTACHMENT_LINKS, BOTTOM_NAV_STYLES, TRACKING_EVENTS } from '@/lib/constants/bottom-navigation'
import type { AttachmentLink } from '@/lib/types/bottom-navigation'

interface AttachmentLinksProps {
  className?: string
  onLinkClick?: (linkId: string, href: string) => void
}

/**
 * 外部链接组件
 * 渲染"我的待办"和"小游戏"等外部链接
 */
export function AttachmentLinks({ className, onLinkClick }: AttachmentLinksProps) {
  // 记录每个按钮的引用以测量宽度
  const linkRefs = useRef<Array<HTMLAnchorElement | null>>([])
  const [maxLinkWidth, setMaxLinkWidth] = useState<number | null>(null)

  const measureAndSetMaxWidth = useCallback(() => {
    const widths = linkRefs.current.map((el) => (el ? el.offsetWidth : 0))
    if (widths.length === 0) return
    const nextMax = Math.max(...widths)
    setMaxLinkWidth((prev) => (prev !== nextMax ? nextMax : prev))
  }, [])

  // 初次渲染与窗口尺寸变化时，计算最大宽度并统一设置
  useEffect(() => {
    const raf = requestAnimationFrame(measureAndSetMaxWidth)
    const handleResize = () => {
      // 使用 rAF 避免频繁 reflow
      requestAnimationFrame(measureAndSetMaxWidth)
    }
    window.addEventListener('resize', handleResize)
    return () => {
      cancelAnimationFrame(raf)
      window.removeEventListener('resize', handleResize)
    }
  }, [measureAndSetMaxWidth])

  // 处理链接点击事件
  const handleLinkClick = (link: AttachmentLink, event: React.MouseEvent<HTMLAnchorElement>) => {
    // 安全检查
    const secureLink = createSecureLink(link.href)
    
    // 如果安全检查失败，阻止默认行为
    if (secureLink.onClick && !secureLink.onClick(event.nativeEvent)) {
      event.preventDefault()
      return
    }

    // 调用回调函数进行埋点追踪
    onLinkClick?.(link.id, link.href)

    // 开发环境日志
    if (process.env.NODE_ENV === 'development') {
      console.info('Attachment link clicked:', {
        id: link.id,
        title: link.title,
        href: link.href
      })
    }
  }

  return (
    <div
      className={cn("attachment-container", className)}
      role="navigation"
      aria-label="外部功能链接"
    >
      <div className="attachment-box">
        {ATTACHMENT_LINKS.map((link, index) => {
          const secureLink = createSecureLink(link.href)
          
          return (
            <div
              key={link.id}
              className="box-list"
            >
              <a
                href={link.href}
                target={link.target || '_blank'}
                rel={link.rel || 'noopener'}
                className="box-list-link"
                ref={(el) => {
                  linkRefs.current[index] = el
                }}
                style={maxLinkWidth ? { width: maxLinkWidth } : undefined}
                onClick={(event) => handleLinkClick(link, event)}
                aria-label={`访问${link.title}`}
              >
                {link.title}
              </a>
            </div>
          )
        })}
      </div>
    </div>
  )
}

